package fr.esigelec.ping25;

import java.io.DataOutputStream;

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class BatterieActivity extends Activity
{
	Button bEcouter, bStop;
	TextView affichage;
	public static TextView texte;
	
	boolean running;
	
	Traitement trait;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    	System.out.println("Go !");
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        bEcouter = (Button) findViewById(R.id.bEcoute);
        bStop = (Button) findViewById(R.id.bStop);
        affichage = (TextView) findViewById(R.id.tvAffichage);
        texte = (TextView) findViewById(R.id.texte);
        
        bEcouter.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				System.out.println("Clic !");
				
				(new Start()).start();
			}
		});
        
        bStop.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				(Toast.makeText(getApplicationContext(), "Stop !", 1)).show();

				running = false;
			}
		});
    }
    
    
    
    
    
    
    
    
    private class Start extends Thread
    {
    	public void run()
    	{
	    	int bufferSize = AudioRecord.getMinBufferSize(11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
			
			short[] bufferAudio = new short[2048];
			Complex[] bufferComplexe = new Complex[2048];
			Complex[] fftDone = new Complex[2048];
			int[] amplitude = new int[2048];
			
			DataOutputStream dos = null;
			
			
			AudioRecord audioRecord = null;
			
			try
			{
				//dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "buffer.pcm"))));
				
				
				audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
				
				audioRecord.startRecording();
				
				running = true;
				
				int nbreSamples = 0;
				
				int bufferReadResult = 0;
				
				while(running)
				{
//					System.out.println("Vérification des dernieres cases du buffer audio AVANT TRAVAIL : ");
//					System.out.println("Case 2047 : " + bufferAudio[2047]);
//					System.out.println("Case 4095 : " + bufferAudio[4095]);
					
					bufferReadResult = audioRecord.read(bufferAudio, 0, 2048);
//					System.out.println(bufferReadResult + " short on été lus (passe 1)");
//					
//					System.out.println("Vérification des dernieres cases du buffer audio ENTRE PASSES : ");
//					System.out.println("Case 2047 : " + bufferAudio[2047]);
//					System.out.println("Case 4095 : " + bufferAudio[4095]);
//					
//					bufferReadResult = audioRecord.read(bufferAudio, 2048, 2048);
//					System.out.println(bufferReadResult + " short on été lus (passe 2)");
					
					
					
//					System.out.println("Vérification des dernieres cases du buffer audio : ");
//					System.out.println("Case 2047 : " + bufferAudio[2047]);
//					System.out.println("Case 4095 : " + bufferAudio[4095]);
//					
//					System.out.println("On a " + bufferSize + " dispo");
					
					for(int j = 0 ; j < 2048 ; j++)
					{
//						nbreSamples++;
						
						bufferComplexe[j] = new Complex((double) bufferAudio[j], (double) 0);
						
						
						
						//texte.setText(texte.getText() + ", " + bufferAudio[j]);
						//System.out.println("Valeur du Buffer audio à la case " + j + " : " + bufferAudio[j] + " | nombre de samples : " + nbreSamples);
						//dos.writeShort(bufferAudio[j]);
					}
					
					/*String texte = "";
					
					System.out.println("\nVérification du contenu du buffer audio :");
					for(int p = 0 ; p < 4096 ; p++)
					{
						texte += bufferAudio[p] + ", ";
					}
					System.out.println(texte);
					
					texte = "";
					
					System.out.println("\nVérification du contenu du buffer complexe :");
					for(int p = 0 ; p < 4096 ; p++)
					{
						System.out.println("Case " + p);
						texte += bufferComplexe[p].re() + ", ";
					}
					System.out.println(texte);*/
					
					fftDone = FFT.fft(bufferComplexe);
					System.out.println("Taille du fftDone : " + fftDone.length);
					
//					System.out.println("Affichage du fftDone");
					
//					String texte = "";
					
					for(int x = 0 ; x < 2048 ; x++)
					{
						amplitude[x] = (int) java.lang.Math.sqrt((fftDone[x].re() * fftDone[x].re()) + (fftDone[x].im() * fftDone[x].im()));
					}
					
					System.out.println("Affichage de l'amplitude :");
//					for(int d : amplitude)
//					{
//						System.out.println(d);
//					}
					
					Thread t = new Affichage(amplitude);
					t.start();
					
					//running = false;
				}
				
				audioRecord.stop();
				
				//audioRecord.stop();
				//dos.flush();
				//dos.close();
				
			} catch (Exception e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			finally
			{
				audioRecord.stop();
				audioRecord.release();
			}
    	}
    }
    
    
    
    
    
    private class Affichage extends Thread
    {
    	int[] tableau = null;
    	String ligne = "";
    	
    	public Affichage(int[] t)
    	{
    		tableau = t;
    		
    		System.out.println("Constructeur : tableau de taille " + tableau.length);
    	}
    	
    	public void run()
    	{    		
    		System.out.println("\t================================================");
    		
    		int max_magnitude = -10000000;
    		int max_index = -1;
    		
    		for(int i = 1 ; i < tableau.length ; i++)
    		{
    			//System.out.println("Case " + i + " : " + tableau[i]);
    			
    			if(tableau[i] > max_magnitude)
    			{
    				max_magnitude = tableau[i];
    				//System.out.println("\tNouvelle magnitude : " + max_magnitude);
    				max_index = i;
    				//System.out.println("\tNouvel index : " + max_index);
    			}
    		}
    		
    		//System.out.println("max_index = " + max_index);
    		
    		System.out.println("\tFréquence la plus élevée : " + max_index * 44100 / 2048);
    		
    		System.out.println("\t================================================");
    	}
    }
}